package com.hzh.page.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzh.page.common.utils.JwtUtils;
import com.hzh.page.common.utils.MD5;
import com.hzh.page.dao.AuthenticationUserMapper;
import com.hzh.page.pojo.*;
import com.hzh.page.service.AuthenticationRoleService;
import com.hzh.page.service.AuthenticationUserRoleService;
import com.hzh.page.service.AuthenticationUserService;
import com.hzh.page.service.RegionService;
import com.hzh.page.vo.AuthenticationUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口
 *
 * @author chenzw
 * @date 2022-11-03
 */
@Service
public class AuthenticationUserServiceImpl extends ServiceImpl<AuthenticationUserMapper, AuthenticationUser> implements AuthenticationUserService {

    @Autowired
    private AuthenticationUserRoleService userRoleService;
    @Autowired
    private AuthenticationRoleService roleService;

    @Autowired
    private RegionService regionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(AuthenticationUserVO userVO) {
        AuthenticationUser user = this.baseMapper.selectById(userVO.getId());
        //修改用户名或用户密码
        if (user != null) {
            if (userVO.getPassWord() != null && !("".equals(userVO.getPassWord()))) {
                user.setPassWord(MD5.encrypt(userVO.getPassWord()));
            }
            if (userVO.getUserName() != null && !userVO.getUserName().isEmpty()) {
                user.setUserName(userVO.getUserName());
            }
            //修改用户的地区信息
            if (userVO.getRegionId() != null) {
                user.setRegionId(userVO.getRegionId());
            }
            if (userVO.getRoleState() != null) {
                user.setRoleState(userVO.getRoleState());
            }
            this.baseMapper.updateById(user);
            //修改用户的角色信息
            AuthenticationUserRoleEntity roleId = userRoleService.getOne(new QueryWrapper<AuthenticationUserRoleEntity>().eq("user_id", user.getId()));
            if (!userVO.getRoleId().equals(roleId.getRoleId())) {
                //修改用户的角色信息
                //1删除原有的角色信息，新增新的角色信息
                userRoleService.remove(new QueryWrapper<AuthenticationUserRoleEntity>().eq("user_id", user.getId()));
                AuthenticationUserRoleEntity userRoleEntity = new AuthenticationUserRoleEntity();
                userRoleEntity.setRoleId(userVO.getRoleId());
                userRoleEntity.setUserId(user.getId());
                userRoleService.save(userRoleEntity);
            }
        }
    }

    @Override
    public AuthenticationUserVO getUserInfoById(Integer id) {
        AuthenticationUserVO userVO = new AuthenticationUserVO();
        AuthenticationUser user = baseMapper.selectById(id);
        if (user != null) {
            AuthenticationUserRoleEntity userRole = userRoleService.getOne(new QueryWrapper<AuthenticationUserRoleEntity>().eq("user_id", user.getId()));
            if (userRole != null) {
                AuthenticationRoleEntity roleInfo = roleService.getById(userRole.getRoleId());
                BeanUtils.copyProperties(user, userVO);
                userVO.setRegionName(regionService.getById(user.getRegionId()).getValue());
                if (roleInfo != null) {
                    userVO.setRole(roleService.getRoleMenuByRoleId(roleInfo.getId()));
                }
            }
            return userVO;
        } else {
            return null;
        }
    }

    @Override
    public IPage<AuthenticationUserVO> listPage(Page<AuthenticationUser> pageParam, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtils.getUserId(token);
        AuthenticationUser user = baseMapper.selectById(userId);
        Integer regionId = user.getRegionId();
        RegionEntity regionInfo = regionService.getById(regionId);
        Page<AuthenticationUser> userList = null;
        if ("全国".equals(regionInfo.getValue())) {
            userList = baseMapper.selectPage(pageParam, null);
        } else {
            userList = baseMapper.selectPage(pageParam, new QueryWrapper<AuthenticationUser>().eq("region_id", regionId));
        }
        List<AuthenticationUser> records = userList.getRecords();
        List<AuthenticationUserVO> userVOList = records.stream().map(record -> {
            return getUserInfoById(record.getId());
        }).collect(Collectors.toList());
        IPage<AuthenticationUserVO> userVOPage = new Page<>();
        BeanUtils.copyProperties(pageParam, userVOPage);
        userVOPage.setRecords(userVOList);
        return userVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Integer userId) {
        //1、删除用户，2、删除用户角色表中的关联信息
        baseMapper.deleteById(userId);
        userRoleService.remove(new QueryWrapper<AuthenticationUserRoleEntity>().eq("user_id", userId));
    }

    @Override
    public void updateStatus(Integer userId, Boolean roleState) {
        AuthenticationUser user = new AuthenticationUser();
        user.setRoleState(roleState);
        user.setId(userId);
        baseMapper.updateById(user);
    }

    @Override
    public List<AuthenticationMenuEntity> getMenusByUserId(Integer userId) {

        return baseMapper.getMenusByUserId(userId);
    }
}
